package com.androidmtk;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidMTK extends Activity {
	public static final String TAG = "AndroidMTK";
	private static final int REQUEST_ENABLE_BT = 2;

	// Local Bluetooth adapter
	private static BluetoothAdapter mBluetoothAdapter;
	private static SharedPreferences sharedPreferences;

	// Preferences Bluetooth device string
	private static String GPS_bluetooth_id = "-1";

	private ProgressDialog dialog;
	private TextView messageField;

	// Keys
	public static final String KEY_TOAST = "TOAST";
	public static final String MESSAGEFIELD = "textSwitcher";
	public static final String KEY_PROGRESS = "progressCompleted";
	public static final String CLOSE_PROGRESS = "closeProgressDialog";

	// Output date
	private String file_time_stamp;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		Log.v(TAG, "+++ ON CREATE +++");

		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		// Clear all preferences. FOR TESTING!
		// SharedPreferences.Editor editor = sharedPreferences.edit();
		// editor.clear();
		// editor.commit();

		// Create the layout with a couple of buttons
		setContentView(R.layout.main);
		Button buttondel = (Button) findViewById(R.id.buttondel);
		buttondel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Perform action on click
				delLog();
			}
		});
		Button buttonget = (Button) findViewById(R.id.buttonget);
		buttonget.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Perform action on click
				getLog();
			}
		});
		Button buttonhelp = (Button) findViewById(R.id.buttonhelp);
		buttonhelp.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Perform action on click
				startActivity(new Intent(getBaseContext(), Help.class));
			}
		});

		messageField = (TextView) findViewById(R.id.messageField);

		checkHasBluetoothAdapter();
		// Check if Bluetooth is enabled
		if (!mBluetoothAdapter.isEnabled()) {
			askUserToEnableBluetooth();
		}

		Log.i(TAG,
				"+++ GPS bluetooth device: "
						+ sharedPreferences
								.getString("bluetoothListPref", "-1"));

	}

	/**
	 * Ask user to enable bluetooth
	 */
	private void askUserToEnableBluetooth() {

		// No, ask user to start it
		Intent enableBtIntent = new Intent(
				BluetoothAdapter.ACTION_REQUEST_ENABLE);
		startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

	}

	/**
	 * Check if device has Bluetooth
	 */
	private void checkHasBluetoothAdapter() {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			// Device does not support Bluetooth
			Toast.makeText(this, "Bluetooth is not available",
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled
			} else {
				// User did not enable Bluetooth or an error occured
				finish();
			}
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.preferences:
			startActivity(new Intent(getBaseContext(),
					MyPreferenceActivity.class));
			return true;
		case R.id.help:
			startActivity(new Intent(getBaseContext(), Help.class));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void delLog() {
		Log.v(TAG, "+++ ON delLog +++");

		if (!isGPSSelected())
			return;

		dialog = ProgressDialog.show(this, "Clearing log", "Please wait...",
				true, false);

		// Start a thread to do the deleting
		DelThread thread = new DelThread(DelThreadHandler);
		thread.start();

		Log.d(TAG, "++++ Done: delLog()");
	}

	// Define a Handler
	final Handler DelThreadHandler = new Handler() {
		public void handleMessage(Message msg) {
			dialog.dismiss();
		}
	};

	/** Nested class that performs the deleting of the log */
	private class DelThread extends Thread {
		Handler mHandler;

		DelThread(Handler h) {
			mHandler = h;
		}

		public void run() {
			GPSrxtx gpsdev = new GPSrxtx(mBluetoothAdapter, GPS_bluetooth_id);
			if (gpsdev.connect()) {
				// Send the command to clear the log
				try {
					gpsdev.sendCommand("PMTK182,6,1");

					// Wait for reply from the device
					gpsdev.waitForReply("PMTK001,182,6,3");
					gpsdev.close();
				} catch (BluetoothException e) {
					e.printStackTrace();
					messageField.setText(e.getMessage());
				}
			}

			Message msg = mHandler.obtainMessage();
			mHandler.sendMessage(msg);
		}
	}

	public void getLog() {
		Log.v(TAG, "+++ ON getLog +++");

		if (!isGPSSelected())
			return;

		// Start a thread to get the log
		// Create a unique file for writing the log files to
		Time now = new Time();
		now.setToNow();
		file_time_stamp = now.format("%Y-%m-%d_%H%M");
		DownloadBinRunnable downloadBin = new DownloadBinRunnable(
				downLoadThreadHandler, file_time_stamp,
				convertToGPXThreadHandler);
		Thread downloadThread = new Thread(downloadBin);
		downloadThread.start();
		Log.d(TAG, "++++ Done: getLog()");

	}

	/**
	 * Check if Bluetooth GPS device selected
	 */
	private boolean isGPSSelected() {

		GPS_bluetooth_id = sharedPreferences.getString("bluetoothListPref",
				"-1");
		if ("-1".equals(GPS_bluetooth_id) || GPS_bluetooth_id.length() == 0) {
			// No GPS device selected in the preferences
			AlertDialog.Builder builder = new AlertDialog.Builder(
					AndroidMTK.this);
			builder.setMessage("Please select a GPS device in the preferences first!");
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							Intent preferenceActivity = new Intent(
									getBaseContext(),
									MyPreferenceActivity.class);
							startActivity(preferenceActivity);
						}
					});
			builder.show();
			return false;
		}
		return true;
	}

	// Define a Handler for Download
	private final Handler downLoadThreadHandler = new Handler() {

		private ProgressDialog dialogDownload = null;

		public void handleMessage(Message msg) {

			if (dialogDownload == null) {
				dialogDownload = new ProgressDialog(AndroidMTK.this);
				dialogDownload
						.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				dialogDownload.setMessage("Downloading GPS log");
				dialogDownload.setCancelable(false);
				dialogDownload.setMax(100);
			} else if (msg.getData().containsKey(CLOSE_PROGRESS)) {
				dialogDownload.hide();
			}

			if (msg.getData().containsKey(KEY_PROGRESS)) {
				dialogDownload.show();
				dialogDownload.setProgress(msg.getData().getInt(KEY_PROGRESS));
			}

			if (msg.getData().containsKey(KEY_TOAST)) {
				String message = msg.getData().getString(KEY_TOAST);
				Toast.makeText(AndroidMTK.this, message, Toast.LENGTH_LONG)
						.show();
			}

		}
	};

	// Define a Handler for Converting Bin to GPX
	final Handler convertToGPXThreadHandler = new Handler() {

		private ProgressDialog dialogConvertToGPX;

		public void handleMessage(Message msg) {

			if (dialogConvertToGPX == null) {
				dialogConvertToGPX = new ProgressDialog(AndroidMTK.this);
				dialogConvertToGPX
						.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				dialogConvertToGPX.setMessage("Converting GPS log to GPX file");
				dialogConvertToGPX.setCancelable(false);
				dialogConvertToGPX.setMax(100);
			} else if (msg.getData().containsKey(CLOSE_PROGRESS)) {
				dialogConvertToGPX.hide();
			}
			if (msg.getData().containsKey(KEY_PROGRESS)) {
				dialogConvertToGPX.show();
				int percentageComplete = msg.getData().getInt(KEY_PROGRESS);
				dialogConvertToGPX.setProgress(percentageComplete);
			}

			if (msg.getData().containsKey(KEY_TOAST)) {
				String message = msg.getData().getString(KEY_TOAST);
				Toast.makeText(AndroidMTK.this, message, Toast.LENGTH_LONG)
						.show();
			}
			if (msg.getData().containsKey(MESSAGEFIELD)) {
				String message = msg.getData().getString(MESSAGEFIELD);
				messageField.setText(message);
			}

		}
	};

	// **** Restarting code ****

	public void hotStart(View v) {
		performRestart(1);
	}

	public void warmStart(View v) {
		performRestart(2);
	}

	public void coldStart(View v) {
		performRestart(3);
	}

	private void performRestart(int mode) {

		if (!isGPSSelected())
			return;
		dialog = ProgressDialog.show(this, "Performing", "Please wait...",
				true, false);

		// Start a thread to do the restarting
		RestartRunnable restartRunnable = new RestartRunnable(
				RestartThreadHandler, mode);
		Thread restartThread = new Thread(restartRunnable);
		restartThread.start();

	}

	// Define a Handler
	final Handler RestartThreadHandler = new Handler() {
		public void handleMessage(Message msg) {
			dialog.dismiss();
			Toast.makeText(AndroidMTK.this, (String) msg.obj, Toast.LENGTH_LONG)
					.show();
		}
	};

	public void close(View v) {
		finish();
	}

	public static BluetoothAdapter getmBluetoothAdapter() {
		return mBluetoothAdapter;
	}

	public static SharedPreferences getSharedPreferences() {
		return sharedPreferences;
	}

	public static String getGPS_bluetooth_id() {
		return GPS_bluetooth_id;
	}

}
